package org.javaboy.demo.dao;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.javaboy.demo.model.User;

import java.io.IOException;
import java.util.List;

public class UserMapper {
    private SqlSession sqlSession = null;
    public UserMapper() throws IOException {
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
                //读取配置文件
                .build(Resources.getResourceAsStream("mybatis-conf.xml"));
        //获取到一个 SqlSession 对象
        sqlSession = sqlSessionFactory.openSession();
    }

    /**
     * 两个规范：
     * 1. XML 文件中的 namespace 就是当前类名
     * 2. XML 文件中操作的 id 就是当前方法名
     * @param user
     * @return
     */
    public int addUser(User user) {
        int i = sqlSession.insert("org.javaboy.demo.dao.UserMapper.addUser", user);
        sqlSession.commit();
        return i;
    }

    public int deleteById(int id) {
        int i = sqlSession.delete("org.javaboy.demo.dao.UserMapper.deleteById", id);
        sqlSession.commit();
        return i;
    }

    public int updateUser(User user) {
        int i = sqlSession.update("org.javaboy.demo.dao.UserMapper.updateUser", user);
        sqlSession.commit();
        return i;
    }
    
    public List<User> getAllUsers() {
        return sqlSession.selectList("org.javaboy.demo.dao.UserMapper.getAllUsers");
    }
}
